element plus 使用 icon 图标(两种方式) 您所在的位置:网站首页 element ui 爱心图标 element plus 使用 icon 图标(两种方式)

element plus 使用 icon 图标(两种方式)

2024-01-14 17:51| 来源: 网络整理| 查看: 265

前提

Element UI 和 Element Plus 对 Icon 图标 的使用方式改变较大,在此记录。

Element UI Icon 图标:使用CSS 类名方式;Element Plus Icon 图标:使用Vue 组件方式; 安装 npm npm install @element-plus/icons-vue yarn yarn add @element-plus/icons-vue 使用

必须先安装 element-plus,可使用命令:

npm 方式:npm install element-plus --save

yarn 方式:yarn add element-plus

如果对整个 vue3项目的搭建有疑问可查看《基于 Vite + Vue3 + TS + sass + router + element-plus 的项目搭建》

方式一

main.ts中引入:

代码第 6 行,引入所有图标;

代码第 10-13行,全局注册图标;

import { createApp } from 'vue' import './style.css' import App from './App.vue' import ElementPlus from 'element-plus' import 'element-plus/dist/index.css' import * as ElementPlusIconsVue from '@element-plus/icons-vue' const app = createApp(App) // 全局注册 for (const [key, component] of Object.entries(ElementPlusIconsVue)) { app.component(key, component) } app.use(ElementPlus) .mount('#app')

有两种使用方式:

结合 el-icon 使用,提供了额外的属性,如:is-loading等;直接使用 SVG 图标,当做一般的 svg 使用;

效果:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-muWQyl9P-1675921794620)(./images/2-1.png)]

方式二

步骤一:新建文件 src/utils/elements.ts

// 全部小写,且加上 el-icon-,如:el-icon-xxx。这样更清晰 export const toIconLine = (value: string) => { return 'el-icon-' + value.replace(/(A-Z)/g, '-$1').toLocaleLowerCase() }

步骤二:main.ts中引入

代码第6-7行,引入所有图标和转行方法;代码第11-16行,全局注册图标组件,且使用方式有改变; import { createApp } from 'vue' import './style.css' import App from './App.vue' import ElementPlus from 'element-plus' import 'element-plus/dist/index.css' import * as ElementPlusIconsVue from '@element-plus/icons-vue' import { toIconLine } from './utils/elements' const app = createApp(App) // 全局注册图标 会牺牲一点性能 el-icon-xxx for(let i in ElementPlusIconsVue) { let name = toIconLine(i); console.log(name); app.component(name, (ElementPlusIconsVue as any)[i]) } app.use(ElementPlus) .mount('#app')

步骤三:App.vue 中设置 svg 高宽

svg { width: 1em; height: 1em; }

同样,有两种使用方式:

结合 el-icon 使用,提供了额外的属性,如:is-loading等;直接使用 SVG 图标,当做一般的 svg 使用;

效果:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IK4lZ8Df-1675921794621)(./images/2-1.png)]

总结

方式一 和 二 的区别:

前者直接使用大驼峰方式使用图标,如 。后者使用小驼峰加横杠,如 。更清晰,避免组件重名。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有